package com.dao; 

import java.text.*; 
 import java.util.*; 
 import java.sql.*; 

import com.adopters.ConnectionManager;
import com.beans.UserBean;
 
 public class UserDAO { 
	 static Connection con = null; 
	 static ResultSet rs = null;
	 public static UserBean login(UserBean bean) {
		 
		 //preparing some objects for connection 
		 Statement stmt = null;
		 String username = bean.getUserName();
		 String password = bean.getPassword();
		 String searchQuery = "select * from user_details where USER_NAME='" + username + "' AND PASSWORD='" + password + "'"; 
		 
		 
		 try { 
			 //connect to DB 
			 con = ConnectionManager.getConnection();
			 stmt=con.createStatement(); 
			 rs = stmt.executeQuery(searchQuery); 
		
			 boolean more = rs.next(); 
			 bean.setDept((String)rs.getString("dept"));
			 // if user does not exist set the isValid variable to false 
			 if (!more) {
				 System.out.println("Sorry, you are not a registered user! Please sign up first");
				 bean.setValid(false);
			}
			 
			 //if user exists set the isValid variable to true
			else if (more) { 
				String User_Name = rs.getString("User_Name"); 
				bean.setUserName(User_Name); 
				bean.setValid(true);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		 //some exception handling 
		finally { 
			if (rs != null) {
				try { 
					rs.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
				rs = null;
			} if (stmt != null) {
				try { 
					stmt.close();
				} catch (Exception e) {
					e.printStackTrace();
				} 
				stmt = null; 
			} if (con != null) { 
				try { con.close(); 
			} catch (Exception e) { 
				e.printStackTrace();
			}
				con = null;
			
			} 
		}
		return bean; 
	}
}
